package codeRandomThoughts.Test144二叉树的前序遍历;

import codeRandomThoughts.utils.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        preorder(root, result);
        return result;
    }

    public void preorder(TreeNode root, List<Integer> result) {
        if (root == null) {
            return;
        }
        result.add(root.val);
        preorder(root.left, result);
        preorder(root.right, result);
    }

    /**
     * 迭代法
     *
     * @param root
     * @return
     */
    public List<Integer> preorderTraversal2(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();

        //先把根节点放入栈中
        stack.push(root);

        while (!stack.isEmpty()) {
            //根节点入栈
            TreeNode node = stack.pop();
            //下面这段判断逻辑很重要 防止死循环
            if (node!=null){
                result.add(node.val);
            }else {
                continue;
            }

            //右孩子入栈
            stack.push(node.right);

            //左孩子入栈
            stack.push(node.left);
        }
        return result;
    }
}
